package com.ymall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description:Cookie 工具类 用户Tomcat集群后，访问统一域名，指向不同Tomcat服务器造成的Session信息不一样的问题
 * Time:2018/01/08
 * Auther:evenlee
 */
@Slf4j
public class CookieUtil {

    public static final String COOKIE_DOMAIN = ".ymall.com";
    public static final String COOKIE_NAME = "YMALL_LOGIN_TOKEN";

    //写Cookie
    public static void writeLoginToken(HttpServletResponse httpServletResponse,String token){
        Cookie ck = new Cookie(COOKIE_NAME,token);
        ck.setDomain(COOKIE_DOMAIN);
        ck.setPath("/");//cookie 有效作用
        ck.setMaxAge(60*60*12); //60秒*60*12= 12个小时
        ck.setHttpOnly(true);// 防止通过脚本的方式访问修改cookie，提高了一部分安全性
        log.info("[Write Cookie]--Cookie Name：{} & Cookie Value：{}",ck.getName(),ck.getValue());
        httpServletResponse.addCookie(ck);
    }

    public static String readeLoginToken(HttpServletRequest httpServletRequest){
        Cookie[] cks = httpServletRequest.getCookies();
        for (Cookie cookie:cks ) {
            if (StringUtils.equals(cookie.getName(),COOKIE_NAME)){
                log.info("[Reade Cookie]--Cookie Name：{} & Cookie Value：{}",cookie.getName(),cookie.getValue());
                return cookie.getValue();
            }
        }
        return null;
    }

    public static void delLoginToken(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cks = request.getCookies();
        for (Cookie cookie:cks ) {
            if (StringUtils.equals(cookie.getName(),COOKIE_NAME)){
                log.info("[Delete Cookie]--Cookie Name：{} & Cookie Value：{}",cookie.getName(),cookie.getValue());
                cookie.setDomain(COOKIE_DOMAIN);
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                return;
            }
        }
    }
}
